package net.sourceforge.stripes.security;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.config.BootstrapPropertyResolver;
import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.exception.StripesServletException;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.util.ReflectUtil;

public class StripesSecurityFilter
	extends StripesFilter
{
	/** Key used to lookup the name of the SecurityManager class used to configure Stripes security. 
	 *  This class must implement StipesSecurityManager.*/
	public static final String SECURITY_MANAGER = "SecurityManager.Class";
	/** Key used to lookup the url to be used to forward if the user is unauthorized. */
	public static final String UNAUTHORIZED_RESOLUTION = "UnauthorizedResolutionURL";
	private static Log log = Log.getInstance(StripesSecurityFilter.class);

	private static StripesSecurityManager securityManager;
	private static Resolution unauthorizedResolution;

	public static StripesSecurityManager getSecurityManager()
	{
		return securityManager;
	}

	public static Resolution getUnauthorizedResolution()
	{
		return unauthorizedResolution;
	}

	@Override
	public void init(FilterConfig filterConfig)
		throws ServletException
	{		
		BootstrapPropertyResolver bootstrap = new BootstrapPropertyResolver(filterConfig);
		String securityMangerClassName = bootstrap.getProperty(SECURITY_MANAGER);

		String unauthorizedURL = bootstrap.getProperty(UNAUTHORIZED_RESOLUTION);

		// Set up the Security Manager
		if (securityMangerClassName != null)
		{
			try
			{
				Class<?> clazz = ReflectUtil.findClass(securityMangerClassName);
				securityManager = (StripesSecurityManager) clazz.newInstance();
			}
			catch (Exception e)
			{
				log.fatal(e, "Could not instantiate specified SecurityManager. Class name specified was ", "[",
							securityMangerClassName, "].");
				throw new StripesServletException("Could not instantiate specified Configuration. "
					+ "Class name specified was [" + securityMangerClassName + "].", e);
			}
		}
		else
		{
            log.fatal("Could not instantiate specified SecurityManager. Class name specified was ",
                      "[", securityMangerClassName, "].");
            throw new StripesServletException("Could not instantiate specified Configuration. " +
                    "Class name specified was [" + securityMangerClassName + "].");

		}
		
		if (unauthorizedURL != null)
		{
			unauthorizedResolution = new ForwardResolution(unauthorizedURL);
		}
		else
		{
            log.warn("Could not find unauthorizedURL ",
                      "URL specified was [", unauthorizedURL, "].");
            unauthorizedResolution = null;

		}	
		super.init(filterConfig);
	}
}
